import { useEffect, useRef } from 'react';
import flooim from './imfloo-2.0.0.miniprogram.js';
import { Button } from '@antmjs/vantui';
import { CSpaceCustom } from '@vh-mobile/pro-components';
import { toast } from '@vh-mobile/pro-utils';

export default function Index() {
  const imRef = useRef<any>();
  const username = 'zhouyingchao';
  const password = '123456';

  useEffect(() => {
    const config = {
      autoLogin: true,
      dnsServer: 'https://dns.lanyingim.com/v2/app_dns',
      appid: 'btgedzqtdtsy',
      ws: true,
      logLevel: process.env.NODE_ENV === 'production' ? 'off' : 'debug',
    };

    imRef.current = flooim(config);

    imRef.current.on({
      onRosterMessage: (meta: any) => {
        console.log('onRosterMessage', meta);
        toast.show(`收到消息：${meta.content}`);
      },
    });
  }, []);

  const asyncRegister = () => {
    imRef.current.userManage
      .asyncRegister({
        username: username,
        password: password,
      })
      .then((res: any) => {
        console.log(res);
      })
      .catch(() => {});
  };

  const login = () => {
    imRef.current.login({
      //TODO: change name to username
      name: username,
      password: password,
    });
  };

  const getConversationList = () => {
    const list = imRef.current.userManage.getConversationList();
    console.log('===================');
    console.log(list);
    console.log('===================');
  };

  const sendRosterMessage = () => {
    imRef.current.sysManage.sendRosterMessage({
      uid: '6606179797008', // 用户id，只有单聊时使用
      content: '我是消息111', // 消息文本内容
      type: 'text',
    });
  };

  const getRosterMessageByRid = () => {
    const localMessages = imRef.current.rosterManage.getRosterMessageByRid('6606179797008');
    console.log('===================');
    console.log(localMessages);
    console.log('===================');
  };

  return (
    <CSpaceCustom direction="horizontal">
      <Button type="primary" onClick={asyncRegister}>
        注册账号
      </Button>

      <Button type="primary" onClick={login}>
        登录IM
      </Button>

      <Button type="primary" onClick={getConversationList}>
        获取会话列表
      </Button>

      <Button type="primary" onClick={sendRosterMessage}>
        发送消息
      </Button>

      <Button type="primary" onClick={getRosterMessageByRid}>
        获取聊天消息
      </Button>
    </CSpaceCustom>
  );
}
